<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\model\LoginLogModel;
use app\admin\service\AdminService;
use app\admin\service\MenuService;
use app\Request;
use think\facade\View;

/**
 * 登陆管理
 */
class Login extends AdminController
{

    public $noNeedLogin = ['*'];

    /**
     * 管理员登陆页面
     *
     * @Author tanruizheng
     * @DateTime 2021-07-09
     * @param Request $request
     * @return void
     */
    public function login(Request $request){
        //记住我
        if(AdminService::autologin()){
            return redirect('/admin/Dashboard/index');
        }
        return View::fetch('login');
    }

    /**
     * 管理员登陆操作
     *
     * @Author tanruizheng
     * @DateTime 2021-07-09
     * @return void
     */
    public function doLogin(Request $request){
        $username = $request->post('username');//用户名
        $password = $request->post('password');//密码
        $captcha = $request->post('captcha');//验证码
        $rememberMe = $request->post('rememberMe');//记住我
        if(!$username) {
            return self::createFail('用户名不能为空');
        }
        if(!$password) {
            return self::createFail('密码不能为空');
        }
        if(!$captcha) {
            return self::createFail('验证码不能为空');
        }
        if(!captcha_check($captcha)){
            // 验证失败
            return self::createFail('验证码错误!');
        };
        //登陆操作
        $result = AdminService::instance()->doLogin($username, $password, $rememberMe ? 86400 : 0);
        return json($result);

    }

    /**
     * 管理员退出登陆
     *
     * @Author tanruizheng
     * @DateTime 2021-07-09
     * @return void
     */
    public function loginOut(){
        session(null);
        cookie('keeplogin',null);
        return self::createSuccess('退出登陆成功');
    }
}
